﻿using CMS.AOP;
using CMS.Auth;
using CMS.DataAccess;
using CMS.Excep;
using CMS.Model;
using CMS.Utils;

namespace CMS.ServiceProvider
{
    public class UserServiceProvider:BaseServiceProvider<UserModel>
    {
        public UserServiceProvider()
        {
            this.udpInstance.RegBeforeSaveAction(new UserSaveAction());
        }
        public string TryLogin(string userCode, string password)
        {
            if (string.IsNullOrWhiteSpace(userCode) || string.IsNullOrWhiteSpace(password))
            {
                throw new MyArgException($"登录必须提供用户名和密码");
            }
            var user = qryInstance
                .Where(CondCollection.True().EqIgnoreCase(nameof(UserModel.UserCode), userCode).Eq(nameof(UserModel.Password),MyUtils.Md5(password)))
                .First();
            if (user == null)
                throw new MyAuthorizationException($"用户{userCode}登陆失败");
            return new UserTokenManager().MakeToken(user.Pk, user.UserName, user.IsAdmin);
        }

        public void ChangePassword(string userId, string password,string validPassword)
        {
            if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(password)) throw new MyArgException($"必须提供用户ID和密码");
            var optUser = ServiceLoader.GetOptUser();
            var myInfo = qryInstance.Get(optUser.UserId);
            if (myInfo.Password != MyUtils.Md5(validPassword)) throw new MyArgException($"密码验证失败");
            if (!optUser.IsAdm && userId != optUser.UserId) throw new MyOptException($"非管理员只能修改自己的密码");
            if (optUser.UserId != userId)
            {
                var userInfo = qryInstance.Get(userId);
                userInfo.Password = MyUtils.Md5(password);
                Save(userInfo);
            }
            else
            {
                myInfo.Password = MyUtils.Md5(password);
                Save(myInfo);
            }
        }
    }
}
